package com.project.lk.nurseapp.utils;

import android.content.Context;
import android.util.Log;


import com.project.lk.nurseapp.base.BaseApp;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import okhttp3.Cache;
import okhttp3.Callback;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;


/**
 * 功能介绍：
 * 项目名：
 * 模块名称：
 * 作者：LK
 * 日期：2018/1/9
 * 修改日期：
 */
public class OkHttpUtils {

    private static OkHttpClient mOkHttpClient;

    private static OkHttpUtils mOkHttpUtils;

    //创建OkHttpUtils的构造方法
    private OkHttpUtils(Context context) {
        mOkHttpClient = getOkHttpClient();
        int size = 1024 * 1024 * 10;//10M
        Cache cache = new Cache(context.getCacheDir(), size);
    }

    //   利 用单例模式实现创建OkHttpClient的对象
    public static OkHttpClient getOkHttpClient() {

        if (mOkHttpClient == null) {
            synchronized (OkHttpClient.class) {
                mOkHttpClient = new OkHttpClient();
            }

        }
        return mOkHttpClient;
    }

    //利用单例模式获取OkHttpUtils的对象
    public static OkHttpUtils getOkHttpClientUtils(Context context) {

        if (mOkHttpUtils == null) {
            synchronized (OkHttpUtils.class) {
                mOkHttpUtils = new OkHttpUtils(context);
            }
        }
        return mOkHttpUtils;
    }

    // GET同步网络请求

    //得到一个Requset的对象
    private Request getRequest(String url) {
        Request request = new Request.Builder().get().url(url).build();


        return request;
    }

    //得到一个Response的对象
    private Response getResponse(String url) throws IOException {
        Request request = getRequest(url);
        Response response = mOkHttpClient.newCall(request).execute();
        return response;
    }

    //得到一个ResponseBody的对象
    private ResponseBody getResponseBody(String url) throws IOException {
        Response response = getResponse(url);
        if (response.isSuccessful()) {
            ResponseBody body = response.body();
            return body;
        }
        return null;
    }

    //获取Get同步的String 类型的数据
    public static String getOkHttpGetString(String url) throws IOException {
        //利用OkHttpUtils的对象调用gerRespnose方法

        ResponseBody requestBody = mOkHttpUtils.getResponseBody(url);

        return requestBody.string();
    }

    //返回值为byte[]类型
    public static byte[] getBytesFromUrl(String url) throws IOException {
        ResponseBody body = mOkHttpUtils.getResponseBody(url);
        if (body != null) {
            byte[] bytes = body.bytes();
            return bytes;
        }
        return null;
    }

    //返回值为字节流类型
    public static InputStream getStreamFromUrl(String url) throws IOException {
        ResponseBody body = mOkHttpUtils.getResponseBody(url);
        if (body != null) {
            InputStream stream = body.byteStream();
            return stream;
        }
        return null;
    }

    //获取Get异步的网络请求
    public static void getDataAsync(String url, Context context, Callback callback) {
        Request request = getOkHttpClientUtils(context).getRequest(url);
        //Request request = new Request.Builder().get().url(url).build();
        getDefualtOkhttp().newCall(request).enqueue(callback);

    }

    //post异步请求json数据  new FormBody.Builder()
    public  static void postJsonAsync(String url,RequestBody body,Callback callback){

        Request request = new Request.Builder().url(url).post(body).build();
        getDefualtOkhttp().newCall(request).enqueue(callback);
    }

    //post异步请求上传文件数据
    public static void postFileAsync(String url, List<String> pathList, MediaType type,String files,Callback callback){
        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM);
        //得到一个RequestBody的对象
        if (pathList!=null){
            for (int i = 0; i < pathList.size(); i++) {
                Log.d("MLOG", String.valueOf(i) + "count");
                RequestBody body = RequestBody.create(type, new File(pathList.get(i)));
                builder.addFormDataPart("files", pathList.get(i), body);
            }
        }
        RequestBody filesBody = builder.build();
        //得到一个Request的对象
        Request request = new Request.Builder().url(url).post(filesBody).build();
        mOkHttpClient.newCall(request).enqueue(callback);
    }

    /**
     * 开启缓存
     */
    private static OkHttpClient getDefualtOkhttp() {
        return new OkHttpClient.Builder()
                //开启缓存
                .cookieJar(new CookieManger(BaseApp.getInstance()))
                .cache(getResponseCache())
                .addInterceptor(new HttpLoggingInterceptor())
                //添加缓存拦截
                .addNetworkInterceptor(new CacheInterceptor())
                .build();
    }

//获取缓存对象
    /**
     * Android/data/包名/cache/response
     */
    public static Cache getResponseCache() {
        File externalCacheDir = BaseApp.getInstance().getExternalFilesDir(AppConfig.RESPONSE_CACHE);
        return new Cache(externalCacheDir, AppConfig.DEFAULT_RESPONSE_CACHE_SIZE);
    }

    private static final Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Response originalResponse = chain.proceed(chain.request());
            return originalResponse.newBuilder().removeHeader("Pragma")
                    .header("Cache-Control", String.format("max-age=%d", 10)).build();//设置了缓存时间为10秒
        }
    };



}
